﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noesis.Javascript;
using System.IO;
using A2DFramework.RuleEngine.Exceptions;

namespace A2DFramework.RuleEngine
{
    public class RuleEngine:IDisposable
    {
        private JavascriptContext context;
        private string rulePath;
        private bool throwExceptionIfRuleFileNotFound = true;
        private IJavascriptGenerator jsGenerator = null;

        public RuleEngine()
        {
            context = new JavascriptContext();
            this.throwExceptionIfRuleFileNotFound = true;
            jsGenerator = new JavascriptGenerator();
        }
        public RuleEngine(bool throwExceptionIfRuleFileNotFound):this()
        {
            this.throwExceptionIfRuleFileNotFound = throwExceptionIfRuleFileNotFound;
        }
        public void SetJavascriptGenerator(IJavascriptGenerator jsGenerator)
        {
            this.jsGenerator = jsGenerator;
        }


        public void SetParameter(string variableName, object variableValue)
        {
            context.SetParameter(variableName, variableValue);
        }
        
        public void BindRulePath(string rulePath)
        {
            if (!File.Exists(rulePath) && this.throwExceptionIfRuleFileNotFound)
                throw new NotFoundRuleFileException(rulePath);

            this.rulePath = rulePath;
        }

        public void Process()
        {
            string realJs = jsGenerator.GenerateJS();
            context.Run(realJs);
        }

        public void Dispose()
        {
            if (this.context != null)
            {
                this.context.Dispose();
                this.context = null;
            }
        }

        public Int32 GetInt32(string variableName)
        {
            object o = this.context.GetParameter(variableName);
            return Int32.Parse(o.ToString());
        }
        public decimal GetDecimal(string variableName)
        {
            object o = this.context.GetParameter(variableName);
            return decimal.Parse(o.ToString());
        }

        public bool GetBoolean(string variableName)
        {
            object o = this.context.GetParameter(variableName);
            return bool.Parse(o.ToString());
        }
    }
}